package com.finger.forest;

import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.esri.arcgisruntime.ArcGISRuntimeEnvironment;
import com.esri.arcgisruntime.geometry.GeometryEngine;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.location.LocationDataSource;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.view.Callout;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.LocationDisplay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol;
import com.finger.forest.base.BaseActivity;
import com.finger.forest.base.BaseView;
import com.finger.forest.base.CommonKey;
import com.finger.forest.base.SystemConfig;
import com.finger.forest.http.presenter.RegisterPresenter;
import com.finger.forest.utils.ClickUtils;
import com.finger.forest.utils.encode.PrefsUtil;

import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import butterknife.OnClick;

import static org.litepal.LitePalApplication.getContext;

/**
 * @author jzj
 * @date 2020/11/3
 * @desc 测点
 */
public class MeasurePointActivity extends BaseActivity<RegisterPresenter> implements BaseView {

    private static final String TAG = "MeasurePointActivity";

    /**
     * 返回
     */
    @BindView(R.id.btn_back)
    ImageView backIv;

    /**
     * 清空
     */
    @BindView(R.id.btn_right)
    TextView clearTv;

    private MapView mMapView;

    private LocationDisplay mLocationDisplay;

    GraphicsOverlay mGraphicsOverlay = new GraphicsOverlay();

    @Override
    protected int setView() {
        return R.layout.activity_measure_point;
    }

    @Override
    protected void receiveData() {

    }

    @Override
    protected void initializeView() {
        mMapView = findViewById(R.id.mapView);
        setupMap();

        //定位当前位置
        setupLocationDisplay(false);

        mMapView.getGraphicsOverlays().add(mGraphicsOverlay);

        mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, mMapView) {

            @Override
            public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
                Log.i(TAG, "onSingleTapConfirmed: " + motionEvent.toString());

                // get the point that was clicked and convert it to a point in map coordinates
                android.graphics.Point screenPoint = new android.graphics.Point(Math.round(motionEvent.getX()),
                        Math.round(motionEvent.getY()));
                // create a map point from screen point
                Point mapPoint = mMapView.screenToLocation(screenPoint);
                // convert to WGS84 for lat/lon format
                Point wgs84Point = (Point) GeometryEngine.project(mapPoint, SpatialReferences.getWgs84());

                // create a textview for the callout
                TextView calloutContent = new TextView(getApplicationContext());
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.setMargins(50,50,50,50);//4个参数按顺序分别是左上右下
                calloutContent.setLayoutParams(layoutParams);

                calloutContent.setPadding(10,10,10,10);
                calloutContent.setTextColor(getResources().getColor(R.color.colorBlue));
                calloutContent.setSingleLine();
                // format coordinates to 4 decimal places
                calloutContent.setText("纬度: " + String.format("%.6f", wgs84Point.getY()) + ", 经度: " + String.format("%.6f", wgs84Point.getX()));

                // get callout, set content and show
                Point point1 = new Point(wgs84Point.getX(), wgs84Point.getY()+0.0024, SpatialReferences.getWgs84());
                final Callout mCallout = mMapView.getCallout();
                mCallout.setLocation(point1);
                mCallout.setContent(calloutContent);
                Callout.Style style = new Callout.Style(MeasurePointActivity.this, R.xml.callout_style_point);
                mCallout.setStyle(style);
                mCallout.show();

                // center on tapped point
                mMapView.setViewpointCenterAsync(mapPoint);

                //显示位置图标
                Point point2 = new Point(wgs84Point.getX(), wgs84Point.getY(), SpatialReferences.getWgs84());
                BitmapDrawable bitmapDrawable = (BitmapDrawable) ContextCompat.getDrawable(MeasurePointActivity.this, R.drawable.icon_measure_point);
                PictureMarkerSymbol locationMarker = new PictureMarkerSymbol(bitmapDrawable);
                locationMarker.setOffsetY(13);
                Graphic pointGraphic2 = new Graphic(point2, locationMarker);
                mGraphicsOverlay.getGraphics().add(pointGraphic2);

                return true;
            }
        });
    }

    @Override
    protected void loadDataFromServer() {

    }

    private void showImageAtMap(int res, MotionEvent e) {
        BitmapDrawable startDrawable = (BitmapDrawable) ContextCompat.getDrawable(getContext(), res);
        final PictureMarkerSymbol pinSourceSymbol;
        try {
            pinSourceSymbol = PictureMarkerSymbol.createAsync(startDrawable).get();
            pinSourceSymbol.loadAsync();
            pinSourceSymbol.addDoneLoadingListener(new Runnable() {
                @Override
                public void run() {
                    //添加新图形
                    Point point = mMapView.screenToLocation(new android.graphics.Point(Math.round(e.getX()), Math.round(e.getY())));
                    Graphic pinSourceGraphic = new Graphic(point, pinSourceSymbol);
                    mGraphicsOverlay.getGraphics().add(pinSourceGraphic);
                }
            });
            pinSourceSymbol.setOffsetY(20);
        } catch (InterruptedException | ExecutionException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            mLocationDisplay.startAsync();
        } else {
            Toast.makeText(MeasurePointActivity.this, getResources().getString(R.string.location_permission_denied), Toast.LENGTH_SHORT).show();
        }
    }

    private void setupMap() {
        if (mMapView != null) {
            ArcGISRuntimeEnvironment.setLicense(CommonKey.LICENSE);
            mMapView.setAttributionTextVisible(false);
            Basemap.Type basemapType = Basemap.Type.IMAGERY;
            ArcGISMap map = new ArcGISMap(basemapType, SystemConfig.latitude, SystemConfig.longitude, SystemConfig.mapLevel);
            mMapView.setMap(map);
        }
    }

    @OnClick({R.id.btn_back, R.id.btn_right, R.id.btn_location, R.id.btn_zoom_in , R.id.btn_zoom_out })
    public void onClick(View v) {
        if (ClickUtils.isFastClick()) { //防止重复点击
            switch (v.getId()) {

                //返回
                case R.id.btn_back:
                    finish();
                    break;

                //右边按钮
                case R.id.btn_right:
                    //清空图形
                    mGraphicsOverlay.getGraphics().clear();

                    //去掉标记
                    mMapView.getCallout().dismiss();
                    break;

                //定位
                case R.id.btn_location:
                    setupLocationDisplay(true);
                    break;

                //地图放大
                case R.id.btn_zoom_in:
                    mMapView.setViewpointScaleAsync(mMapView.getMapScale() * 0.5);
                    break;

                //地图缩小
                case R.id.btn_zoom_out:
                    mMapView.setViewpointScaleAsync(mMapView.getMapScale() * 2);
                    break;

                default:
                    break;
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        // pause MapView
        mMapView.pause();
    }

    @Override
    public void onResume() {
        super.onResume();
        // resume MapView
        mMapView.resume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // dispose MapView
        mMapView.dispose();
    }

    private void setupLocationDisplay(boolean boo) {
        mLocationDisplay = mMapView.getLocationDisplay();
        mLocationDisplay.startAsync();

        mLocationDisplay.addLocationChangedListener(new LocationDisplay.LocationChangedListener() {
            @Override
            public void onLocationChanged(LocationDisplay.LocationChangedEvent locationChangedEvent) {
                LocationDataSource.Location location=locationChangedEvent.getLocation();
                Point point=location.getPosition();
                Log.i(TAG, "定位===》"+point.toString());

                if (boo){
                    // center on tapped point
                    mMapView.setViewpointCenterAsync(point,SystemConfig.mapScale);
                }

                mLocationDisplay.removeLocationChangedListener(this);
            }
        });
    }

    @Override
    public void onSuccess(Object model, int tag, String msg) {

    }

    @Override
    public void onError(int errcode, int tag, String message) {

    }
}
